package org.bluweb.g4wicket;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.wicket.behavior.AbstractBehavior;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.template.PackagedTextTemplate;
import org.apache.wicket.util.template.TextTemplate;

@SuppressWarnings("serial")
public abstract class G4WicketBehaviour extends AbstractBehavior {

	private final static Random idGenerator = new Random();
	
	private String id;
	
	protected G4WicketBehaviour() {
		this( String.valueOf( idGenerator.nextInt( 1000 ) ) );
	}

	protected G4WicketBehaviour( String id ) {
		this.id = id;
	}
	
	protected String getId() {
		return this.id;
	}
	
	@Override
	public void renderHead(IHeaderResponse response) {
		response.renderJavascriptReference( "http://www.google.com/jsapi" );
	}

	protected String getCSS( String name ) {

		StringBuilder css = new StringBuilder( "<style type=\"text/css\">" );
		css.append( new PackagedTextTemplate(this.getClass(), name ).asString() );
		css.append( "</style>" );
		return css.toString();
	}
	
	protected String getJavaScript( String name, Map<String,Object> parameters ) {

		TextTemplate template = new PackagedTextTemplate(this.getClass(), name );
		
		String script;
		if( parameters == null ) {
			parameters = new HashMap<String,Object>();
		}

		parameters.put( "id", this.getId() );
		
		script = template.asString( parameters );
		
		return script;
	}

	protected void execute( String script, G4WicketEvent event ) {

		event.getComponent().add(new AttributeAppender( event.getEvent(), new Model<String>( script ), ";"));		
	}
}
